import numpy
import pylab
from scipy.optimize import fmin_tnc
from scipy.interpolate import interp1d


def Envelope(x,y,low=True):
    def diff(x):
        return x[1:]-x[:-1]

    upperind = numpy.where(diff(numpy.sign(diff(y))) < 0)[0] + 1
    lowerind = numpy.where(diff(numpy.sign(diff(y))) > 0)[0] + 1
    f = 0;
    l = len(y)-1;
    upperind = numpy.array([f] +list(upperind)+[l]);
    lowerind = numpy.array([f] +list(lowerind)+[l]);
    xi = range(f , l+1);
    upperenv = interp1d(upperind, y[upperind], kind='linear')(xi)
    lowerenv = interp1d(lowerind, y[lowerind], kind='linear')(xi)
    if low:
        return x,lowerenv
    else:
        return x,upperenv

if __name__ == '__main__':
    def mkdata():
        x=numpy.linspace(0,1,100)
        y=numpy.random.random(100)*numpy.sin(numpy.pi*x)
        return x,y

    x,y=mkdata()
    ex,ey=Envelope(x,y)
    pylab.figure(num=1)
    pylab.ion()
    pylab.clf()
    pylab.grid(True)
    pylab.plot(x,y)
    pylab.plot(ex,ey)
    pylab.show()
